<?php
namespace app\admin\controller;
class Index extends \app\admin\controller\Common{

    public function index()
    {
        if (request()->isGet()) {
            $tpl = input('tpl');
            $this -> view -> nickname = 'thinkphp';
            if ($tpl) {
                $this -> success('','',$this -> fetch($tpl));
            }else{
                return $this -> fetch();
            }
        }elseif (request()->isPost()) {
            config('default_ajax_return','json');
            config('default_return_type','json');
            $api = input('api');
            $this -> $api();
        }
    }

    public function main(){
        $this -> success('加载成功','',$this->fetch());
    }
    
    // 清理缓存
    public function runtime(){
        if (request()->isPost()) {
            if ($type = input('type')) {
                switch ($type) {
                    case 'cache':
                        \think\Cache::clear();
                        break;
                    case 'tpl':
                        deldir(TEMP_PATH);
                        break;
                    case 'all':
                        deldir(RUNTIME_PATH);
                        break;
                    
                    default:
                        # code...
                        break;
                }
            }
            $this -> success('成功清理系统缓存！');
        }
    }

    // 修改自己的密码
    public function password(){
        if (request()->isGet()) {
            $this -> fetchform();
        }elseif (request()->isPost()) {
            $oldpassword = input('oldpassword');
            $password = input('password');
            $passwordtwo = input('passwordtwo');
            if ($passwordtwo != $password) {
                $this -> error('两次密码输入不一致');
            }
            $id = 1;
            $m = \think\Db::name('user');
            $user = $m->find($id);
            if (crypt_pwd($oldpassword,$user['salt']) == $user['password']) {
                if (false !== $m -> where('id',$id) -> setField('password',crypt_pwd($password,$user['salt']))) {
                    $this -> success('修改成功');
                }else{
                    $this -> error($m -> getDbError());
                }
            }else{
                $this -> error('密码错误');
            }
        }
    }

    // 显示用户信息
    public function userinfo(){
        if (request() -> isGet()) {
            if ($user = \app\user\model\User::get(input('id'))) {
                $this -> assign('user',$user);
                $this -> success('','',$this -> fetch());
            }else{
                $this -> error('用户不存在！');
            }
        }elseif (request() -> isPost()) {
            $this -> success('获取成功');
        }
    }

    // webuploader上传
    public function upload(){
        config('default_return_type','json');
        $file = request()->file('file');
        $info = $file->move('./upload/image');
        if(false !== $info){
            $this -> success('上传成功！','',[
                'pathname'=>substr(str_replace('\\', '/', $info -> getPath().'/'.$info -> getBasename()), strlen('./upload')),
                'name' => $info->getBasename()
                ]);
        }else{
            $this -> error('上传失败！','',$file->getError());
        }
    }

    // 编辑器上传
    public function ueditor(){
        config('default_return_type','json');
        $config = [
            'catcherPathFormat'=>'/image/{yyyy}{mm}{dd}/{time}{rand:6}',
            'fileManagerListPath'=>'/file/',
            'filePathFormat'=>'/file',
            'imageManagerListPath'=>'/image/',
            'imagePathFormat'=>'/image',
            'scrawlPathFormat'=>'/image/{yyyy}{mm}{dd}/{time}{rand:6}',
            'snapscreenPathFormat'=>'/image',
            'videoPathFormat'=>'/video',
        ];
        $data = new \ebcms\Ueditor($config);
        return $data->output();
    }

    // 附件地址替换
    public function replaceattachbaseurl(){
        if (request() -> isPost()) {
            $dbpre = \think\Config::get('database.prefix');
            \think\Db::execute('UPDATE '.$dbpre.'content_body SET `body`=replace(`body`, :fromstr, :tostr)',['fromstr'=>input('fromstr'),'tostr'=>input('tostr')]);
            // \think\Db::execute('UPDATE '.$dbpre.'content_content SET `ext`=replace(`ext`, :fromstr, :tostr)',['fromstr'=>input('fromstr'),'tostr'=>input('tostr')]);
            $this -> success('替换成功！');
        }elseif (request() -> isGet()) {
            $this -> fetchform();
        }
    }

    // 数据字典缓存
    private function asyncdata(){
        $request = request();
        $res = array();
        // 超级管理员标识
        $res['super_admin'] = session('super_admin')?1:0;
        // 普通管理员权限
        $res['rules'] = $this -> get_rules(session('user_id'));
        $res['recommend_url'] = url('recommend/admin.recommend/push');
        $res['config'] = $this -> getconfig();
        $res['root'] = get_root();
        $this -> success('加载成功','',$res);
    }

    private function get_rules($user_id){
        if (true == session('super_admin')) {
            return [];
        }
        // 根据角色获取有权限的节点id
        $where = [];
        if ($group_ids = \think\Db::name('auth_access') -> where('uid','eq',session('user_id')) -> column('group_id')) {
            $rule_ids  = \think\Db::name('auth_group') -> where(['id'=>['in',$group_ids],'status'=>1]) -> column('rules');
            $rule_ids = implode(',', $rule_ids);
            $rule_ids = array_unique(explode(',', $rule_ids));
            if ($rule_ids) {
                $where['id'] = ['in',$rule_ids];
            }else{
                $where['id'] = ['eq',-1];
            }
        }
        $where['status'] = 1;
        $rules = \think\Db::name('auth_rule') -> where($where) -> column('name');
        foreach ($rules as &$rule) {
            $rule = md5($rule);
        }
        return $rules;
    }

    private function mymenu(){
        $where = [];
        if (!session('super_admin')) {
            // 根据角色获取有权限的菜单id
            if ($group_ids = \think\Db::name('auth_access') -> where('uid','eq',session('user_id')) -> column('group_id')) {
                $menu_ids  = \think\Db::name('auth_group') -> where(['id'=>['in',$group_ids],'status'=>1]) -> column('menus');
                $menu_ids = implode(',', $menu_ids);
                $menu_ids = array_unique(explode(',', $menu_ids));
                if ($menu_ids) {
                    $where['id'] = ['in',$menu_ids];
                }else{
                    $where['id'] = ['eq',-1];
                }
            }
        }
        $where['status'] = ['in',[1,2]];
        $data = \think\Db::name('menu') -> where($where) -> order('sort desc,id asc') ->select();
        foreach ($data as &$v) {
            $v['url'] = urlencode(url($v['url']));
        }
        $this -> success('获取成功！','',['rows'=>$data]);
    }

    private function getconfig(){
        $data = array(
            'WebUploader_swf' => '/webuploader/Uploader.swf',
            'WebUploader_server' => url('admin/index/upload'),
            );
        return $data;
    }

    // 字典数据
    private function datadict(){
        if ($datadict = input('datadict')) {
            $_where = array(
                'status' => array('eq',1),
                'field' => array('eq',$datadict),
                );
            if ($cate = \think\Db::name('datadictcate') -> where($_where) -> find()) {
                $_where = array(
                    'status' => array('eq',1),
                    'category_id' => array('eq',$cate['id']),
                    );
                $m = \think\Db::name('datadict');
                if (input('order/a')){
                    $m -> order(input('order/a'));
                }

                $_data = $m -> where($_where) -> select();
                $data = [];
                foreach ($_data as &$v) {
                    $v['value'] = render_str($v['value']);
                    $data[$v['id']] = $v;
                };
                $res = array();
                foreach ($data as $key => $value) {
                    $d = array();
                    $d['id'] = (string)$value['value'];
                    $d['pid'] = isset($data[$value['pid']])?(string)$data[$value['pid']]['value']:'';
                    $d['title'] = $value['title'];
                    $d['remark'] = $value['remark'];
                    $res[$value['value']] = $d;
                }
                $this -> success('','',['rows'=>$res]);
            }else{
                $this -> error('数据不存在！');
            }
        }else{
            $this -> error('数据不存在！');
        }
    }

}